//
//  TabMineActivityDetailViewController.swift
//  kz
//
//  Created by Tech_001 on 18/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import SwiftyJSON

typealias statusBlock = (_ str: String,_ index: Int) -> Void
class TabMineActivityDetailViewController: UIViewController, UIWebViewDelegate{
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var joinButton: UIButton!
    
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
    
    var activityImageHeight: CGFloat?
    var activityImage: UIImage?
    var activity: [String:Any]?
    var _loadView: UIView?
    var listIndex: Int?
    var callBack: statusBlock?
    override func viewDidAppear(_ animated: Bool) {
        if GlobalInfo.detaileActivityBack {
            GlobalInfo.detaileActivityBack=false;
            joinButton.setTitle("客服正在审核", for: .normal)
            joinButton.backgroundColor = UIColor.init(red: 147/255, green: 153/255, blue: 146/255, alpha: 1)
            activity?["actscode"]=5
            UIHelper.alertSimpleMessage(about: "提交成功", withDescription: "", in: self)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.topItem?.title = ""
        webView.delegate = self
        //<meta name='format-detection’ content='telephone=no' />
        let javascript = "document.documentElement.style.webkitUserSelect='none';document.documentElement.style.webkitTouchCallout='none';"//禁止选择
        webView.stringByEvaluatingJavaScript(from: javascript)
        titleLabel.text = activity?["actname"] as? String
        
        
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: "navi_icon_titleLogo"))
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        if self.activityImage != nil {
            let domain :String =  UserDefaults.standard.value(forKey: DefaultKey.USER_DOMAIN) as! String
            let domainScheme :String = UserDefaults.standard.string(forKey: DefaultKey.DOMAIN_SCHEME)!
            let imgurl : String =  activity?["cover"] as? String ?? ""
            let url = URL(string: "\(domainScheme)://\(domain)/iimg/\(imgurl)")
            self.imageView?.sd_setImage(with: url, placeholderImage: imageNamed("img_default_banner"), options: SDWebImageOptions.refreshCached, completed: nil)
            //  imageView.image = self.activityImage!
            imageViewHeightConstraint.constant = activityImageHeight!
            //imageViewHeightConstraint.constant = self.activityImage!.size.height + 12
        }
        
        if UserHelper.getLoginStatus() {
            //          if (activity?["show"] as? String ?? "" == "敬请期待" && activity?["activeapply"] as? Int ?? 0 == 0)  || activity?["show"] as? String ?? "" == "" {
            //              joinButton.isHidden = true
            //             bottomConstraint.constant = -50
            //            }else{
            if activity?["activeapply"] as? String ?? "0" == "0" {
                joinButton.setTitle(activity?["nonactiveapplybtn"] as? String ?? "敬请期待", for: .normal)
            }else if activity?["activeapply"] as? String ?? "0" == "1"{
                joinButton.setTitle(activity?["show"] as? String, for: .normal)
            }
            //            if let canJoin = activity?["canJoin"] as? Bool {
            //                if canJoin == true || joinButton.title(for: .normal) == "自动参与" {
            if let actsCode=activity?["actscode"] as? Int {
                if actsCode == 2  {
                    //joinButton.backgroundColor = UIColor.init(red: 0.08, green: 0.49, blue: 0.98, alpha: 1)
                    joinButton.backgroundColor = UIColor.init(red: 0.99, green: 0.64, blue: 0.16, alpha: 1)
                    joinButton.setTitleColor(UIColor.white, for: .normal)
                }else if actsCode == 3 {
                    joinButton.backgroundColor = UIColor.init(red: 0.99, green: 0.64, blue: 0.16, alpha: 1)
                    joinButton.setTitleColor(UIColor.white, for: .normal)
                }
            }
            //}
            
        }else{
            joinButton.setTitle("申请参与", for: .normal)
        }
        
        /**** HTML Content ****/
        let actid = activity!["actid"] as! String
        
        
        RequestHelper.get(atPath: "/clientsAPIs/activityContent?actid=\(actid)", withCompletion: { data in
            var content = String.init(data: data, encoding: .utf8)
            
            DispatchQueue.main.async {
                //  self.webView.dataDetectorTypes=UIDataDetectorTypes.address
                print("网页内容\(content)")
                self.webView.dataDetectorTypes = UIDataDetectorTypes(rawValue: 0)
                self.webView.loadHTMLString(content!, baseURL: URL.init(string:"\(UserDefaults.standard.string(forKey: DefaultKey.DOMAIN_SCHEME)!)://\(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)!)")!)
            }
        }, withError: { error in
            UIHelper.alertSimpleMessage(about: "刷新失败", withDescription: "服务器异常\(getErrorString())", in: self)
        })
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    
    func callBackBlock(_ block: @escaping statusBlock) {
        
        callBack = block
    }
    
    func postApplySuccess(){
        if callBack != nil {
            callBack!("客服正在审核",listIndex!)
        }
        joinButton.backgroundColor = UIColor.groupTableViewBackground
        joinButton.setTitleColor(UIColor.lightGray, for: .normal)
        joinButton.setTitle("客服正在审核", for: .normal)
        activity?["actscode"]=5
    }
    func dailyPromoVerify(){
        RequestHelper.post(atPath: "/wallet/dailyPromoVerify", withData: ["actid":activity!["actid"] as! String],withCompletion: {data in
            let responseArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            if (responseArray["success"] as? Bool)!{
                if(!responseArray.keys.contains("msg")){
                    let actid=self.activity!["actid"] as! String
                    DispatchQueue.main.async {
                        //  ToolHelper.statisticsPage(pageName: "优惠详情页面-点击申请按钮-填写资料页面")
                        self.navigateWebView(toPath: "/walletm/activityForm?actid=\(actid)&isMobile=true", "申请参与",sign: true)
                        self._loadView?.removeFromSuperview()
                        
                    }
                }
            }else{
                DispatchQueue.main.async {
                    UIHelper.alertSimpleMessage(about: (responseArray["msg"] as? String)!, withDescription: "", in: self)
                    
                }
            }
        }, withError: { error in
            
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "未成功提交申请，请稍后重试。\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
    func applyOldActivty(){
        RequestHelper.post(atPath: "/kz/member/activity/apply", withData: ["id":activity!["actid"] as! String], withCompletion: { data in
            let responseArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            let code = responseArray["c"] as! Int
            DispatchQueue.main.async {
                switch code{
                case 0:
                    self.postApplySuccess()
                case 999, 1150:
                    UIHelper.displayLoginExpireTip(self)
                default:
                    UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
            }
            
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "未成功提交申请，请稍后重试。\(getErrorString())", withDescription: "", in: self)
            }
        })
    }
    
    
    var isEmail = NSString()
    var isMobie = NSString()
    var isAdress = NSString()
    var isRealName = NSString()
    var countclick:Int = 0
    //    var hudView : MBProgressHUD?
    @IBAction func joinButtonClick(_ sender: Any) {
        if !UserHelper.getLoginStatus(){
            LoginViewController.loginIfNeedController(currentController: self) {}
            return
        }
        self._loadView = UIHelper.initLoadView(self, withMessage: "读取中")
        self.view.addSubview(self._loadView!)
        
        self.countclick = self.countclick + 1
        weak var this  = self
        if countclick == 1 {
            //需请求验证玩家详情
            RequestHelper.post(atPath: "/clientsAPIs/GetVerificationState",
                               withData: ["pagetype":"PROMOTION_PAGE"], withCompletion: { data in
                                self.countclick = 0
                                let json = JSON(data)
                                let type = json.stringValue
                                let typeNeedCheck = "SHOW_VERIFICATION_PAGE"
                                //判断新老用户
                                DispatchQueue.main.async {
                                    //                                    this?.hudView?.removeFromSuperview()
                                    self._loadView?.removeFromSuperview()
                                    if type == typeNeedCheck {
                                        RequestHelper.post(atPath: "/clientsAPIs/GetVerificationAction", withData: ["pagetype":"PROMOTION_PAGE"], withCompletion: {data in
                                            let json = JSON(data)
                                            
                                            //                                    DispatchQueue.main.async {
                                            self.isEmail = json["has_email"].stringValue as NSString
                                            self.isMobie = json["has_mobile"].stringValue as NSString
                                            self.isAdress = json["has_address"].stringValue as NSString
                                            self.isRealName = json["has_realname"].stringValue as NSString
                                            
                                            
                                            print(self.isEmail,self.isMobie,self.isAdress,self.isRealName)
                                            
                                            DispatchQueue.main.async {
                                                self._loadView?.removeFromSuperview()
                                                self.showMsgPopView2(title: "优惠验证", subTitle: "尊敬的会员，您未绑定完善个人资料，申请优惠前请您先完善资料！")
                                            }
                                            
                                        }, withError: {error in
                                            
                                            DispatchQueue.main.async {
                                                self._loadView?.removeFromSuperview()
                                                UIHelper.alertSimpleMessage(about: "获取验证信息失败。\(getErrorString())", withDescription: "", in: self)
                                            }
                                        })
                                    }else{
                                        if UserHelper.getLoginStatus() {
                                            if let actsCode=self.activity?["actscode"] as? Int {
                                                GlobalInfo.listActivityBack=true
                                                if(actsCode==1){
                                                    //已自动参与
                                                    UIHelper.alertSimpleMessage(about: "已自动参与", withDescription: "", in: self)
                                                    
                                                }else if(actsCode==2){
                                                    self.applyOldActivty();
                                                }else if(actsCode==3){
                                                    self.dailyPromoVerify();
                                                }else if(actsCode==4){
                                                    //已参与
                                                    UIHelper.alertSimpleMessage(about: "此活动已参与", withDescription: "", in: self)
                                                }else if(actsCode==5){
                                                    //客服正在审核
                                                    UIHelper.alertSimpleMessage(about: "此活动正在审核", withDescription: "", in: self)
                                                }else if(actsCode==6){
                                                    if let error=self.activity?["error"] as? [String] {
                                                        //error.count
                                                        var errorString:String?="";
                                                        for index in 0...(error.count-1){
                                                            if index==(error.count-1) {
                                                                errorString=errorString!+error[index]
                                                            }else{
                                                                errorString=errorString!+error[index]+"\n"
                                                            }
                                                        }
                                                        UIHelper.alertSimpleMessage(about: errorString!, withDescription: "", in: self)
                                                    }else{
                                                        //无法参与
                                                        UIHelper.alertSimpleMessage(about: "此活动无法参与", withDescription: "", in: self)
                                                        
                                                    }
                                                }
                                            }
                                        }else{
                                            LoginViewController.loginIfNeedController(currentController: self) {}
                                        }
                                        
                                    }
                                }
            }, withError: { error in print(error)
                this?.countclick = 0
                DispatchQueue.main.async {
                    self._loadView?.removeFromSuperview()
                    UIHelper.alertSimpleMessage(about: "读取失败", withDescription: "未成功读取活动信息，请稍后重试\(getErrorString())", in: self)
                }
            })
        }
    }
    
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
        self._loadView = UIHelper.initLoadView(self, withMessage: nil)
        self.view.addSubview(self._loadView!)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        self._loadView?.removeFromSuperview()
    }
    func navigateWebView(toPath: String, _ title: String,sign:Bool){
        //https mt 2018.6.4 改 
        let goNext: WebViewController = WebViewController.init()
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        
        goNext.url = url
        goNext.title = title
        goNext.bottomOffset = 0
        goNext.signLoging=sign
        GlobalInfo.webViewController=goNext
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    
    //优惠验证
    func showMsgPopView2(title : NSString,subTitle : NSString){
        
        let bgView :UIView  = UIView.init()
        let buton = UIButton(type: .custom)
        buton.addTarget(self, action: #selector(removeHelpView), for: .touchUpInside)
        bgView.addSubview(buton)
        bgView.backgroundColor = RGBAlpa(1,1,1,0.4)
        bgView.tag = 1003
        let window: UIWindow  = ((UIApplication.shared.delegate?.window)!)!
        window.addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalToSuperview()
            
        }
        buton.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        
        let whiteView :UIView  = UIView.init(frame: UIScreen.main.bounds)
        whiteView.backgroundColor = UIColor.init(white: 1, alpha: 1)
        whiteView.layer.cornerRadius = 5;
        whiteView.layer.masksToBounds = true
        bgView.addSubview(whiteView)
        whiteView.snp.makeConstraints { (make) in
            make.width.equalTo(280)
            make.centerY.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(180)
            //            make.height.equalTo(350)
        }
        
        let  titleBtn : UIButton  = UIButton.init(type: .custom)
        titleBtn.setBackgroundImage(imageNamed("icon_common_pop_window_title_bg"), for: .normal)
        titleBtn.setTitle(title as String, for: .normal)
        titleBtn.adjustsImageWhenHighlighted = false
        titleBtn.titleEdgeInsets = UIEdgeInsets(top: -10,left: 0, bottom: 0, right: 0)
        whiteView.addSubview(titleBtn)
        titleBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(59)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let content =  UITextView.init()
        content.text = subTitle as String
        content.textColor =  HexRGBAlpha(0x333333,1)
        content.textAlignment = .center
        content.isEditable = false
        //        content.numberOfLines = 0
        //        content.adjustsFontSizeToFitWidth = true
        //        content.minimumScaleFactor = 0.8
        content.font = UIFont.systemFont(ofSize: 14)
        whiteView.addSubview(content)
        content.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-50)
            make.height.equalTo(60)
            make.centerX.equalToSuperview()
            make.top.equalTo(titleBtn.snp.bottom).offset(10)
        }
        let cancelBtn : UIButton  = UIButton.init(type: .custom)
        cancelBtn.setTitle("前往验证", for: .normal)
        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: 280-60, height: 40)
        cancelBtn.layer.addSublayer(layerGradient)
        cancelBtn.layer.cornerRadius = 5;
        cancelBtn.layer.masksToBounds = true
        cancelBtn.addTarget(self, action: #selector(jump), for: .touchUpInside)
        whiteView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-100)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
            make.top.equalTo(content.snp.bottom)
        }
    }
    
    @objc func removeHelpView()  {
        PopWindowHelper.dissmissPopView(tag: 1003)
    }
    
    @objc func jump() {
        PopWindowHelper.dissmissPopView(tag: 1003)
        
        DispatchQueue.main.async {
            
            
            let checkUserInfoVC = DiscountsCheckUserInfoVC(nibName:"DiscountsCheckUserInfoVC", bundle:nil)
            checkUserInfoVC.realNameIsHidden = self.isRealName as NSString
            checkUserInfoVC.phoneCheckIsHidden = self.isMobie as NSString
            checkUserInfoVC.phoneCodeIsHidden = self.isMobie as NSString
            checkUserInfoVC.emailIsHidden = self.isEmail as NSString
            checkUserInfoVC.emailCodeIsHidden = self.isEmail as NSString
            checkUserInfoVC.adressIsHidden = self.isAdress as NSString
            
            self.navigationController?.pushViewController(checkUserInfoVC, animated: true)
            
            self.countclick = 0
            
        }
        
    }
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        //        UIApplication.shared.openURL(request.url!)
        //        return false
        let params = request.url?.parametersFromQueryString
        if params != nil{
            let activityId  =  params?["activityId"]
            if activityId != nil{
                let activityIds =  GlobalInfo.activityIds
                if activityIds != nil{
                    if activityIds!.contains(activityId!){
                        print("活动id---")
                        let goNext: WebViewController = WebViewController.init()
                        goNext.url = request.url?.absoluteString
                        goNext.hidesBottomBarWhenPushed = true
                        let urlComponents = NSURLComponents(string: goNext.url ?? "")
                        let queryItems =  urlComponents?.queryItems
                        var isCatch = true
                        if queryItems != nil && queryItems?.count ?? 0 > 0{
                            for item in queryItems!{
                                if item.name == "catch"{
                                    if item.value == "false" {
                                        isCatch = false
                                    }
                                    break
                                }
                            }
                        }
                        goNext.isHelper = isCatch
                        self.navigationController?.navigationBar.topItem?.title = ""
                        //      goNext?.navigationController?.navigationBar.topItem?.title = ""
                        self.navigationController?.pushViewController(goNext, animated: true)
                        return false
                    }
                }
            }
        }
        //        let url = URL.init(string: "https://m.doubo12b.com?activityId=1883771218121")
        //        print("\(url?.parametersFromQueryString) ======")
        print("\(request.url?.parametersFromQueryString)---")
        return true
    }
    
    // 导航栏左边按钮
    func leftButtonActionWithImg(_ image: String) {
        let naviLeftButton = UIButton.init(type: UIButton.ButtonType.custom)
        naviLeftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 22);
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.normal)
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.highlighted)
        naviLeftButton.addTarget(self, action: #selector(doLeftNaviAction), for: UIControl.Event.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: naviLeftButton)
    }
    // 导航栏左边按钮点击
    @objc func doLeftNaviAction() {
        self.navigationController?.popViewController(animated: true)
    }
}
